package org.client.iot.ui.device;

import android.annotation.SuppressLint;
import android.view.View;

import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.FastjsonUtils;
import com.lucky.utils.log.LogUtils;

import org.client.iot.R;
import org.client.iot.databinding.ActivityMechanicalResetBinding;
import org.client.iot.http.ApiService;
import org.client.iot.http.BaseDevReq;
import org.client.iot.http.UpdateReqDto;
import org.client.iot.util.MMKVUtils;
import org.tzw.template.base.BaseActivity;

import java.util.LinkedHashMap;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 机械复位
 */
public class MechanicalResetActivity extends BaseActivity<ActivityMechanicalResetBinding> {
    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarMechanicalReset.toolbarPageHead);
        mRoot.toolbarMechanicalReset.textViewTitle.setText(getString(R.string.mechanical_reset_toolbar_title));
        mRoot.toolbarMechanicalReset.imgConnectState.setVisibility(View.GONE);
    }

    @Override
    protected void initListener() {
        mRoot.toolbarMechanicalReset.imgBack.setOnClickListener(v -> finish());
        mRoot.btnSet.setOnClickListener(v -> {
            mRoot.textViewConnectText.setVisibility(View.VISIBLE);
            mRoot.btnSet.setVisibility(View.GONE);
            devReset();
        });
    }

    // 设备复位
    private void devReset() {
        String params = FastjsonUtils.toJsonString(devResetParams());
        Observable<BaseDevReq<Object>> compose = NetworkApi.createService(ApiService.class, "dev")
                .devReset(RequestBody.create(MediaType.parse("application/json"), params))
                .compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<Object>>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(BaseDevReq<Object> req) {
                if (req == null) {
                    return;
                }
                runOnUiThread(() -> {
                    LogUtils.i("设备复位req==", req.toString());
                    showToastShort(req.getMessage());
                    mRoot.textViewConnectText.setText(req.getMessage() == null ? "" : req.getMessage());
                    mRoot.btnSet.setVisibility(View.GONE);
                });

            }

            @SuppressLint("CheckResult")
            @Override
            public void onFailure(Throwable e) {
                runOnUiThread(() -> showToastLong(e.getMessage()));
            }
        }));
    }

    private Map<String, Object> devResetParams() {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("type", "复位");
        return params;
    }

}